<script setup>
import {ref, computed, onActivated} from 'vue'
import {projectDetail, deleteJobUser, okProject, getProjectHistoryList} from "@/api/project";
import {informations, addInformation, delziliao, meetingList, delmeeting} from '@/api/information';
import {useRoute} from "vue-router";
import {toast} from "@/hook/toast";
import router from "@/router";
import {delay} from "@/utils";
import confirm from "@/libs/confirm";
import AddVue from "./add/index";
import AllotVue from '@/views/project-detail/allot'
import MeetingVue from './meeting/index'
import {Refresh} from '@element-plus/icons-vue'
import RbVue from './rb'
import request from '@/request'
import HistoryVue from  './history'

import {jiemaData} from '@/utils'

const showRb = ref(false)
const projectData = ref({})
// 资料详情
const infomationDataOne = ref({})

// 会议列表
const meetingListData = ref([])

// 添加资料 展示
const addRef = ref(null)
const visible = ref(false)

function editProject(row, e) {
  addRef.value?.editHandle(row)
  addRef.value?.editDoos(e)
}

// 弹出框 某一项宽度
const formLabelWidth = '100px'
const size = ref("default");

// 添加人员展示
const showAllot = ref(false)
const allotRef = ref(null)
// 添加会议展示
const showMeeting = ref(false)
const meetingRef = ref(null)

// 添加成功之后展示的内容
function addSuccess() {
  resetForm()
}

function resetForm() {
  initData()
}

// 编辑
function editHandles(row) {
  addRef.value?.editHandle(row)
}

const loading = ref(false)
const personList = computed(() => {
  const {user_job_info} = projectData.value
  if (!user_job_info || !user_job_info.length) return []
  const roleEnum = {
    '1': '前端',
    '2': '后端',
    '3': 'UI',
  }
  const roleType = {
    '1': '',
    '2': 'success',
    '3': 'warning',
  }
  const statusEnum = {
    0: 'danger',
    1: 'success'
  }
  return user_job_info.map(item => {
    const {shenfen, is_wancheng} = item
    item.role = roleEnum[shenfen] || '未知'
    item.roleType = roleType[shenfen] || ''
    item.tagType = statusEnum[is_wancheng]
    return item
  })
})
//  解码

// const meetingListDatas = computed(() => {
//   const {user_job_info} = projectData.value
//   if (!user_job_info || !user_job_info.length) return []
//   return user_job_info.map(item => {
//     const {shenfen,is_wancheng} = item
//     item.role = roleEnum[shenfen] || '未知'
//     item.roleType = roleType[shenfen] || ''
//     item.tagType = statusEnum[is_wancheng]
//     return item
//   })
// })


const route = useRoute()

const rbData = ref([])

async function initRb(xiangmu_id) {
  const resp = await request({
    url: "/ribao/lists",
    data: {xiangmu_id},
    method: "POST",
  })
  if (!resp.data) resp.data = []
  const {code, data,} = resp
  if (code !== 1) return

  function patchZero(v) {
    return ('0' + v).slice(-2)
  }

  function patchDate(dateStr) {
    const date = new Date(dateStr)
    const [year, month, day] = [date.getFullYear(), date.getMonth() + 1, date.getDate()]
    return `${year}-${patchZero(month)}-${patchZero(day)}`
  }

  const result = data.map(item => {
    const {nickname, content, date, id} = item
    return {
      nickname, html: decodeURIComponent(content),
      date: patchDate(date), id,
    }
  })
  rbData.value = result
  console.log(result, 'rbData')
}

async function initData() {
  const {query} = route
  if (!query.hasOwnProperty('id')) return toast({
    title: '参数错误',
    onClose: () => {
      router.back()
    }
  })
  loading.value = true
  const {id} = query
  initRb(id)
  const resp = await projectDetail({xiangmu_id: id})
  //执行另一个接口
  const resD = await informations({xiangmu_id: id})
  // 执行另一个会议列表
  const resH = await meetingList({xiangmu_id: id})
  console.log(resH, 'respH')
  await delay(300)
  const {code, data, msg} = resp
  const dataInfo = resD.data
  console.log(resH, '会议列表');
  loading.value = false
  if (code !== 1) return toast({
    title: msg, onClose: () => {
      router.back()
    }
  })
  if (!data) return
  projectData.value = data;
  infomationDataOne.value = dataInfo
  meetingListData.value = resH.data

}

async function deleteHandle(id) {
  const resp = await deleteJobUser({job_user_id: id})
  const {code, msg} = resp
  toast({
    title: msg,
    type: code === 1 ? 'success' : 'error'
  })
  if (code !== 1) return
  await initData()
}

function removePerson(row) {
  const {name, id} = row
  confirm({
    title: '删除确认',
    message: `您确定删除 ${name} 吗？`,
    confirmBtnText: '删除',
    cancelBtnText: '取消'
  }).then(() => deleteHandle(id)).catch(() => {
  })
}

function allotHandle(row) {
  showAllot.value = true
  allotRef.value?.initData(row)
}

// 天机会议 弹出框
const rbRef = ref(null)

function meetingProject(row) {
  showMeeting.value = true
  meetingRef.value?.editHandle(row)
}

function addRb(id) {
  showRb.value = true
  rbRef.value?.editHandle(id)
}

async function deleteHandle2(id) {
  const resp = await delziliao({xiangmuziliao_id: id})
  const {code, msg} = resp
  toast({
    title: msg,
    type: code === 1 ? 'success' : 'error'
  })
  if (code !== 1) return
  await initData()
}

function removePerson2(row) {
  const {ziliao_title, id} = row
  confirm({
    title: '删除确认',
    message: `您确定删除 ${ziliao_title} 吗？`,
    confirmBtnText: '删除',
    cancelBtnText: '取消'
  }).then(() => deleteHandle2(id)).catch(() => {
  })
}

async function deleteRb(id) {
  const resp = await request({
    url: "/ribao/del",
    data: {id},
    method: "POST",
  })
  const {code, msg} = resp
  toast({
    title: msg,
    type: code === 1 ? 'success' : 'error'
  })
  if (code !== 1) return
  await initData()
}

function editRb(row) {
  rbRef.value?.editRb(row)
}

function removeRb(row) {
  const {id} = row
  confirm({
    title: '删除确认',
    message: `您确定删除吗？`,
    confirmBtnText: '删除',
    cancelBtnText: '取消'
  }).then(() => deleteRb(id)).catch(() => {
  })
}

function removeMeeting(row) {
  const {id} = row
  confirm({
    title: '删除确认',
    message: `您确定删除吗？`,
    confirmBtnText: '删除',
    cancelBtnText: '取消'
  }).then(() => removeMeetingId(id)).catch(() => {
  })
}

async function removeMeetingId(id) {
  const resp = await delmeeting({huiyi_id: id})
  const {code, msg} = resp
  toast({
    title: msg,
    type: code === 1 ? 'success' : 'error'
  })
  if (code !== 1) return
  await initData()
}

async function confirmHandle(e) {
  const resp = await okProject(e)
  const {code, msg} = resp
  toast({title: msg, type: code === 1 ? 'success' : 'error'})
  if (code !== 1) return
  await initData()
}

const formData = ref({
  content: '',
  date: '',
  xiangmucanyu_id: '',
})

// 弹出框是否展示
const dialog = ref(false)
const dialogTitle = ref('项目完成')

/** 打开导入弹窗 */
async function openDialog(row) {
  const {id} = row
  formData.value.xiangmucanyu_id = id
  dialog.value = true;
}

/** 关闭导入弹窗 */
function closeDialog() {
  dialog.value = false;
}

function handleSubmit(row) {
  dialog.value = false;
  confirmProject()
}

// 图片是否展示
const showViewer = ref(false)
// 图片
const contentPic = ref([])

// 查看富文本 图片
function getpreview(e) {
  if (e.target.nodeName === 'IMG' || e.target.nodeName == 'img') { //判断是否图片标签
    const img = e.target.currentSrc //获取点击图片地址
    contentPic.value = [img]
    onPreview()
  }
}

// 查看图片
function onPreview() {
  showViewer.value = true
}

// 关闭图片
function closeViewer() {
  showViewer.value = false;
};


// 图片是否展示
const showViewer2 = ref(false)
// 图片
const contentPic2 = ref([])

// 查看富文本 图片
function getpreview2(e) {
  if (e.target.nodeName === 'IMG' || e.target.nodeName == 'img') { //判断是否图片标签
    const img = e.target.currentSrc //获取点击图片地址
    contentPic.value = [img]
    onPreview()
  }
}

// 查看图片
function onPreview2() {
  showViewer.value = true
}

// 关闭图片
function closeViewer2() {
  showViewer.value = false;
};


// 下载文件
function handleDownload(row) {
  window.location.href = (row)
  // showViewer.value = false;
  // downloadWord(row.id)
  // .then(res => {
  //   window.location.href = (res.data.url)
  // })
  // .catch(() => {
  // })
}


// 编辑确认完成
async function confirmProject() {
  console.log(formData.value.date, formData.value, '1111');

  const {content, date, xiangmucanyu_id} = formData.value
  const payload = {
    content, date, xiangmucanyu_id
  }
  confirm({
    title: '确认提示',
    message: `您确定设置为已完成状态吗？`,
    confirmBtnText: '完成',
    cancelBtnText: '取消'
  }).then(() => confirmHandle(payload)).catch(() => {
  })
}

function linkTo() {
  router.push({
    name: 'upload',
  })
}

const historyRef = ref(null)
async function allotHistory() {
  const {id} = route.query
  historyRef.value?.open(id)
  // const resp = await getProjectHistoryList({xiangmu_id: id})
}

onActivated(initData)
</script>

<template>
  <div class="detail-container card_wrap scroll_wrap" v-loading="loading">
    <el-descriptions title="项目信息" border>
      <template #extra>
        <el-button
            :icon="Refresh"
            type="primary"
            @click="initData"
        >刷新数据
        </el-button>
      </template>

      <el-descriptions-item>
        <template #label>
          <span>设计状态</span>
        </template>
        <span>{{ projectData.ui_status_text }}</span>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <span>开发状态</span>
        </template>
        <span>{{ projectData.status_text }}</span>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <span>验收状态</span>
        </template>
        <span>{{ projectData.yanshou_status_text }}</span>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <span>项目名称</span>
        </template>
        <span>{{ projectData.name }}</span>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <span>业务公司</span>
        </template>
        <span>{{ projectData.yewu_company_name }}</span>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <span>签单日期</span>
        </template>
        <span>{{ projectData.qiandan_date }}</span>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <span>合同到期日期</span>
        </template>
        <span>{{ projectData.daoqi_date }}</span>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <span>技术备注</span>
        </template>
        <span>{{ projectData.jishu_yaoqiu_content || '无' }}</span>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <span>备注</span>
        </template>
        <span>{{ projectData.content || '无' }}</span>
      </el-descriptions-item>

      <el-descriptions-item>
        <template #label>
          <span>业务员</span>
        </template>
        <span>{{ projectData.yewu_name }}</span>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <span>产品</span>
        </template>
        <span>{{ projectData.chanpin_name }}</span>
      </el-descriptions-item>

    </el-descriptions>
    <!-- <div class="service-wrap">
      <el-descriptions
          title="业务/产品人员"
          :column="4"
          border
          class="margin-top"
      >

      </el-descriptions>
    </div> -->
    <el-row :gutter="20">
      <el-col :span="12">
        <div class="person-list">
          <div class="person-header">
            <span>人员分配</span>
            <div class="header-left">
              <el-space>

                <el-button type="success" plain size="small"
                           @click="allotHandle(projectData.id)">分配人员
                </el-button>
                <el-button type="info" size="small" @click="allotHistory">分配历史</el-button>
              </el-space>

            </div>
          </div>
          <el-table :data="personList" border>
            <el-table-column label="角色" prop="role">
              <template #default="{ row }">
                <el-tag :type="row.roleType">{{ row.role }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="姓名" prop="name"></el-table-column>
            <el-table-column label="开始日期" prop="start_date"></el-table-column>
            <el-table-column label="结束日期" prop="end_date"></el-table-column>
            <el-table-column label="状态">
              <template #default="{ row }">
                <el-tag :type="row.tagType">{{ row.is_wancheng_text }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template #default="{ row }">
                <el-space>
                  <el-button size="small" plain type="danger" @click="removePerson(row)">删除</el-button>
                  <el-button size="small" plain type="primary" @click="openDialog(row)">确认完成</el-button>
                </el-space>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="person-list">
          <div class="person-header">
            <span>会议纪要</span>
            <div class="header-left">
              <el-button type="success" plain size="small"
                         @click="meetingProject(projectData.id)">添加会议
              </el-button>
            </div>
          </div>
          <div v-if="meetingListData.length > 0">
            <el-table :data="meetingListData" border>
              <el-table-column label="会议时间" prop="date" width="120"></el-table-column>
              <el-table-column label="会议内容" width="400" prop="content">
                <template #default="{ row }">
                  <div class="content-img" v-html="jiemaData(row.content)" @click="getpreview($event)">
                  </div>
                  <el-image-viewer v-if="showViewer" :url-list="contentPic" @close="closeViewer"
                                   :z-index="9999"/>
                </template>
              </el-table-column>
              <el-table-column label="会议图片" prop="">
                <template #default="{ row }">
                  <div style="display: flex; align-items: center" v-if="row.huiyi_images_url.length > 0">
                    <div v-if="row.huiyi_images_url[0] !== ''">
                      <el-image :preview-teleported='true' style="width: 60px; height: 60px"
                                v-for="(item3, index3) in row.huiyi_images_url" :key="index3" :src="item3"
                                :preview-src-list="row.huiyi_images_url">
                      </el-image>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="140">
                <template #default="{ row }">
                  <el-space>
                    <!-- <el-button type="primary" plain size="small" @click="editHandles(row)">编辑</el-button> -->
                    <el-button type="danger" plain size="small"
                               @click="removeMeeting(row)">删除
                    </el-button>
                  </el-space>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <div class="person-list">
          <div class="person-header">
            <span>项目日报</span>
            <div class="header-left">
              <el-button type="success" plain size="small"
                         @click="addRb(projectData.id)">添加日报
              </el-button>
            </div>
          </div>
          <div v-if="rbData.length > 0">
            <el-table :data="rbData" border fit>
              <el-table-column label="日报时间" prop="date" width="120"></el-table-column>
              <el-table-column label="日报作者" prop="nickname"></el-table-column>
              <el-table-column label="日报内容" width="450" prop="content">
                <template #default="{ row }">
                  <div class="content-img" v-html="row.html">
                  </div>
                  <el-image-viewer v-if="showViewer" :url-list="contentPic" @close="closeViewer"
                                   :z-index="9999"/>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="160">
                <template #default="{ row }">
                  <el-space>
                    <el-button type="danger" plain size="small"
                               @click="removeRb(row)">删除
                    </el-button>
                    <el-button type="primary" plain size="small"
                               @click="editRb(row)">编辑
                    </el-button>
                  </el-space>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-col>
    </el-row>
    <div class="person-list" v-for="(item, index) in infomationDataOne" :key="index">
      <div class="person-header">
        <span>{{ item.name || '用户数据' }}</span>
        <div class="header-left">
          <el-button size="small" plain type="primary"
                     @click="editProject(projectData.id, item.name)">添加资料
          </el-button>
        </div>
      </div>
      <div v-if="item.lists.length > 0">
        <el-table :data="item.lists" border style="width: 960px">
          <el-table-column label="资料配置项" prop="ziliao_title" width="120"></el-table-column>
          <el-table-column label="内容" width="400" prop="content">
            <template #default="{ row }">
              <div class="content-img" v-html="jiemaData(row.content)" @click="getpreview2($event)">
              </div>
              <!--                  <el-image-viewer v-if="showViewer2" :url-list="contentPic2" @close="closeViewer2"-->
              <!--                                   :z-index="9999"/>-->
            </template>
          </el-table-column>
          <el-table-column label="图片" prop="">
            <template #default="{ row }">
              <div style="display: flex; align-items: center" v-if="row.images.length > 0">
                <div v-if="row.images[0] !== ''">
                  <el-image :preview-teleported='true' style="width: 60px; height: 60px"
                            v-for="(item3, index3) in row.images" :key="index3" :src="item3"
                            :preview-src-list="row.images">
                  </el-image>
                </div>
              </div>
            </template>
          </el-table-column>
          <!-- 文件 -->
          <el-table-column label="文件" prop="files" width="120">
            <template #default="{ row }">
              <div class="svg-margin-right" title="下载" v-for="(item, index) in row.files" :key="index"
                   @click="handleDownload(row.files[index])">
                <div class="export">{{ item }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="140">
            <template #default="{ row }">
              <el-space>
                <el-button type="primary" plain size="small"
                           @click="editHandles(row)">编辑
                </el-button>
                <el-button type="danger" plain size="small"
                           @click="removePerson2(row)">删除
                </el-button>
              </el-space>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 项目资料 -->

    <!-- 循环 -->

    <!-- 表单弹出框 -->
    <el-dialog v-model="dialog" :title="dialogTitle" width="600px" align-center @close="closeDialog">
      <el-form ref="userFormRef" :model="formData" label-width="40px">
        <el-form-item label="完成日期" :label-width="formLabelWidth">
          <el-date-picker v-model="formData.date" type="date" placeholder="请选择日期" :size="size"/>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="formData.content" placeholder="请输入备注" show-word-limit rows="4" type="textarea"
                    autocomplete="off"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <div class="absolute">
      <add-vue ref="addRef" v-model="visible" @add-success="addSuccess"/>
      <allot-vue ref="allotRef" v-model="showAllot" @add-success="addSuccess"/>
      <meeting-vue ref="meetingRef" v-model="showMeeting" @add-success="addSuccess"/>
      <rb-vue ref="rbRef" v-model="showRb" @add-success="addSuccess"/>
      <history-vue ref="historyRef" />
    </div>
  </div>
</template>

<style scoped lang="scss">
.el-table {

  & ::v-deep th.el-table__cell,
  ::v-deep td.el-table__cell {
    // 设置position 使得 子元素不与其产生新的层叠关系
    position: static;
  }
}


.detail-container {
  overflow-y: scroll;

  .service-wrap {
    width: 500px;
  }

  .person-list {
    margin-top: 24px;

    .person-header {
      color: var(--el-text-color-primary);
      font-size: 16px;
      font-weight: bold;
      padding-bottom: 16px;
      display: flex;
      align-items: center;

      .header-left {
        margin-left: 24px;
      }

    }
  }

  .segmentation {
    display: flex;
    justify-content: space-between;

    .person-list {
      margin-top: 24px;

      .person-header {
        color: var(--el-text-color-primary);
        font-size: 16px;
        font-weight: bold;
        padding-bottom: 16px;
        display: flex;
        align-items: center;

        .header-left {
          margin-left: 24px;
        }
      }
    }
  }


  .margin-top {
    margin-top: 24px;
  }

  .header-title {
    color: #3c4353;
    font-weight: bold;
    font-size: 18px;
  }
}
</style>
